/**
 * 
 */
package neptune.web.server.operations;

import neptune.manager.NeptuneManager;
import neptune.manager.connector.Connector;
import neptune.manager.model.topology.Node;
import neptune.web.server.ApplicationManager;
import it.robertobifulco.ias.IncorrectParamsException;
import it.robertobifulco.ias.Operation;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 * 
 */
public class GetVMsHostedOnPm implements Operation {

	public static String ID = "GetVMsHostedOnPm";

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#execute(java.lang.Object[])
	 */
	public Object[] execute(Object[] args) throws IncorrectParamsException,
			Exception {

		String pmId = (String) args[0];

		Connector conn = ApplicationManager.getApplicationManager()
				.getNeptuneManager().getConnector(pmId);
		String[][] vmInfos = conn.getAllDomains();
		String[][] result = new String[vmInfos.length][];

		int i = 0;
		for (String[] vmInfo : vmInfos) {
			// String xenId = vmInfo[0];
			String vmName = vmInfo[1];
			String vmStatus = vmInfo[2];
			// String vmRam = vmInfo[3];

			String controlIp = "-";

			// Se la vm ha un nome significativo per il sistema (nome.exp)
			if (vmName.split(NeptuneManager.EXPID_NODEID_SEPARATOR).length == 2) 
			{
				String expId = vmName
						.split(NeptuneManager.EXPID_NODEID_SEPARATOR)[1];
				String nodeId = vmName
						.split(NeptuneManager.EXPID_NODEID_SEPARATOR)[0];

				/*
				 * Recupera l'indirizzo di controllo del nodo nel seguente modo:
				 * 
				 * 1. Ottiene l'oggetto Experiment
				 * 2. Ottiene l'oggetto Topology
				 * 3. Ottiene l'oggetto Node usando serchNodeIntoTopology(nodeId) 
				 * 4. recupera dall'oggetto Node il control address
				 */
				try
				{
					Node node = ApplicationManager.getApplicationManager()
					.getNeptuneManager().getExperiment(expId).getTopology()
					.searchNodeIntoTopology(nodeId);

					controlIp = node.getControlAddress().getAddress();
				}
				catch(java.lang.Exception e)
				{
					
				}
				
			}

			result[i] = new String[3];
			result[i][0] = vmName;
			result[i][1] = vmStatus;
			result[i][2] = controlIp;
			i++;
		}

		conn.closeConnection();

		return new Object[] { result };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#getDescription()
	 */
	public String getDescription() {
		return "Returns the list of vms hosted by a physical machine";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#getID()
	 */
	public String getID() {
		return ID;
	}

}
